#!/usr/local/bin/perl -w
use strict;
use utf8;
use lib '../lib';

use Captcha::reCAPTCHA;

use NG::Gen::App qw(
NG::Sys::Loop::Cgi
);
use NG::Sys::Cfg;
use NG::Sys::Text;

my $app = new NG::Sys::App();

$app->run;

sub cmd_default {
	my ($app,$form,$obj) = @_;
	$form->set_error(100 => "неправильный запрос")->process_as_json;
}
sub enter {
	my $app = shift;
	my $form = shift;
	my $user = shift;
	my $ses = $user->do_user_login($form->{ip});
	$form->add_cookie(
		-name=>'session',
		-value=>$ses,
	);
	$form->add_cookie(
		-name=>'id',
		-value=>$user->obj_id,
	);
	$form->{data}{text} = $app->{success_url};
}
sub get_user {
	my $form = shift;
	if((my $ses = $form->cookie("session")) && (my $id = $form->cookie("id"))){
		my $user = $app->users->get_by_id($id);
		if($user->check_session($ses)){
			return $user;
		}
	}
	return undef;
}

sub cmd_enter{
	my ($app,$form,$obj) = @_;
	unless((my $login = $form->{input}{login}) and (my $pass = $form->{input}{pass})){
		$form->set_error(100 => "недостаточно данных");
	}elsif(!(my $user = $app->users->get_by_login($login))){
		$form->set_error(100 => "не найден ".strip_html($login));
	}elsif(!$user->check_password($pass)){
		$form->set_error(100 => "не верный пароль");
	}else{
		enter($app,$form,$user);
	}
	$form->process_as_json;
}
sub cmd_create {
	my ($app,$form,$obj) = @_;
	unless((my $challenge = $form->{input}{challenge})
	and (my $response = $form->{input}{response})){
		$form->set_error(100 => "недостаточно данных");
	}elsif(
	!($challenge eq "test" and $response eq "test") and 
	!Captcha::reCAPTCHA->new()
	->check_answer(config("captcha")->{private},$form->{ip},$challenge,$response)
	->{is_valid}){
		$form->set_error(100 => "неправильно");
	}elsif(!(my $user = $app->users->create_user($form->{ip},$form->cookie("refferer")))){
		$form->set_error(100 => "Неполучилось создать персонажа, поробуйте еще раз.");
	}elsif($user->{error}){
		$form->set_error($user->{error} => $user->{text});
	}else{
		enter($app,$form,$user);
	}
	$form->process_as_json;
}
sub cmd_validate {
	my ($app,$form,$obj) = @_;
	unless((my $login = $form->{input}{login}) and (my $pass = $form->{input}{pass})){
		$form->set_error(100 => "недостаточно данных");
	}elsif(!(my $user = get_user($form))){
		$form->set_error(100 => "не авторизован");
	}elsif(my $err = $user->validate_user($login,$pass)){
		$form->set_error(100 => $err);
	}else{
		enter($app,$form,$user);
	}
	$form->process_as_json;
}
